package com.qc31.comlib.choose.car

import android.app.Activity
import android.graphics.Color
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.MarginLayoutParams
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import autodispose2.autoDispose
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.qc31.baselib.base.LazyFragment
import com.qc31.baselib.databinding.IncludeSelectSureBinding
import com.qc31.baselib.rx.RxIo
import com.qc31.baselib.rx.clickThrottle
import com.qc31.baselib.utils.*
import com.qc31.comlib.Keys
import com.qc31.comlib.R
import com.qc31.comlib.databinding.FragmentSearchBinding
import com.qc31.comlib.entity.CarLick

/** @Author Jasper @Time 2020/7/22 @Desc 搜索车辆 */
class SearchFragment(private val isVideo: Boolean = false) :
    LazyFragment<FragmentSearchBinding>(FragmentSearchBinding::inflate) {

    private lateinit var mSureVB: IncludeSelectSureBinding
    private var carInfo: CarLick? = null

    private val mViewModel: SearchViewModel by viewModels()


    override fun initView(view: View) {
        mSureVB = IncludeSelectSureBinding.bind(binding.root)

        mSureVB.tvSure.setText(R.string.desc_com_sure)
        binding.llSearch.visibility = View.VISIBLE
        mViewModel.toastObserver().autoDispose(scopeProvider).subscribe(::toastObserver)
        binding.includeRecycler.recyclerView.layoutManager = LinearLayoutManager(context)
        binding.includeRecycler.recyclerView.adapter = SearchAdapter().apply {
            mViewModel.searchSub.autoDispose(scopeProvider).subscribe {
                if (isAdd) {
                    isAdd = false
                    setNewInstance(it)
                } else {
                    notifyDataSetChanged()
                }
                if (it.size <= 0) {
                    binding.llSearch.visibility = View.VISIBLE
                } else {
                    binding.llSearch.visibility = View.GONE
                }

            }

            setOnItemClickListener { adapter, view, position ->
                hideSoftInput()
                index = position
                notifyDataSetChanged()
                carInfo = data[position]
            }
        }
    }

    override fun initData() {
        mViewModel.wordsObserver().observeOn(RxIo.mainScheduler())
            .autoDispose(scopeProvider).subscribe {
                initWords(it)
            }

        mViewModel.toastObserver().autoDispose(scopeProvider).subscribe(this::toastObserver)

    }

    private var isAdd = true
    override fun initEvent() {
        binding.tvSearchClear.clickThrottle().autoDispose(scopeProvider).subscribe {
            mViewModel.clear()
        }
        binding.tvSearch.clickThrottle().autoDispose(scopeProvider).subscribe {
            isAdd = true
            mViewModel.searchCars(binding.editPlate.text.toString(), isVideo)
        }

        mSureVB.tvSure.clickThrottle().autoDispose(scopeProvider).subscribe {
            if (carInfo == null) {
                context?.toast(R.string.toast_choose_one_car)
                return@subscribe
            } else {
                carInfo?.run {
                    setResultTo(activity as Activity) {
                        putExtra(Keys.INTENT_CAR_ID, carId)
                        putExtra(Keys.INTENT_CAR_NAME, subPlate(carPlate, 14))

                        if (videos != null) putExtra(Keys.VIDEO, videos)
                    }
                    ChooseCars.addCars(
                        carId = carId,
                        carPlate = carPlate,
                        carName = carName,
                        videos = videos,
                        iconLink = iconLink,
                        isVideo = !videos.isNullOrEmpty()
                    )
                }
                activity?.finish()
            }
        }
    }

    private fun initWords(words: List<String>) {
        binding.cflSearch.removeAllViews()
        val lp = MarginLayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT
        )
        lp.leftMargin = 10
        lp.rightMargin = 10
        lp.topMargin = 3
        lp.bottomMargin = 3
        val length: Int = words.size
        for (i in 0 until length) {
            val str: String = words[i]
            val view = TextView(activity)
            view.text = str
            view.setTextColor(Color.BLACK)
            view.setBackgroundResource(R.drawable.bg_flow_optimal)
            view.setOnClickListener {
                binding.editPlate.setText(str)
                binding.editPlate.setSelection(binding.editPlate.text.length)
                isAdd = true
                mViewModel.searchCars(str, isVideo)
            }
            binding.cflSearch.addView(view, lp)
        }
    }

    inner class SearchAdapter :
        BaseQuickAdapter<CarLick, BaseViewHolder>(R.layout.item_search_choose_car) {
        var index: Int = -1
        override fun convert(holder: BaseViewHolder, item: CarLick) {
            item.run {
                holder.run {
                    val check = getView<ImageView>(R.id.ivItemChoose)
                    check.isSelected = index == layoutPosition
                    getView<ImageView>(R.id.ivCarLogo).loadStringDImgError(context, iconLink)
                    setText(R.id.tvCarPlate, carPlate)
                    setText(R.id.tvCarName, carName)
                }
            }
        }

    }
}